package nio;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.StandardCharsets;

/**
 * @author wlz
 * @date 2022-07-06  10:49 下午
 */
@Slf4j
public class MyAIOServer {

    public static void main(String[] args) throws Exception{
        AsynchronousServerSocketChannel serverSocketChannel = AsynchronousServerSocketChannel.open();

        serverSocketChannel.bind(new InetSocketAddress(9000));

        serverSocketChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {

            @SneakyThrows
            @Override
            public void completed(AsynchronousSocketChannel socketChannel, Object attachment) {
                log.info("2-- {}",Thread.currentThread().getName());

                serverSocketChannel.accept(attachment, this);
                log.info(" RemoteAddress: {} ", socketChannel.getRemoteAddress());
                ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

                socketChannel.read(byteBuffer, byteBuffer, new CompletionHandler<Integer, ByteBuffer>() {
                    @Override
                    public void completed(Integer result, ByteBuffer attachment) {
                        log.info("3-- {}", Thread.currentThread().getName());
                        byteBuffer.flip();
                        log.info("接收到的消息: {}", new String(byteBuffer.array(), 0, result));
                        socketChannel.write(ByteBuffer.wrap("helloClient".getBytes(StandardCharsets.UTF_8)));
                    }
                    @Override
                    public void failed(Throwable exc, ByteBuffer attachment) {
                        log.error("failed : {}", exc);
                    }
                });
            }

            @Override
            public void failed(Throwable exc, Object attachment) {
                log.error("failed : {}", exc);
            }
        });

        log.info("1-- {}", Thread.currentThread().getName());
        Thread.sleep(Integer.MAX_VALUE);
    }
}
